<template>
  <div class="upload">
    <el-card>
      <h3 style="text-align: center">{{ $route.query.name }}导入</h3>
      <upload-excel :on-success="onSuccess" />
    </el-card>
  </div>
</template>

<script>
import uploadExcel from '@/components/lib/uploadExcel.vue'
import { sysUserBatch } from '@/api/employees'
//                     导入模块
export default {
  name: '',
  components: { uploadExcel },
  data() {
    return {}
  },
  computed: {},
  created() {},
  methods: {
    async onSuccess({ header, results }) {
      const obj = {
        入职日期: 'timeOfEntry',
        姓名: 'username',
        工号: 'workNumber',
        手机号: 'mobile',
        转正日期: 'correctionTime'
      }
      const arr = results.map((item) => {
        const newObj = {}
        // ['入职时间','姓名']
        // 对每一项的对象进行循环
        // item为数组中的对象
        // console.log(item)
        Object.keys(item).forEach((item2) => {
          // 赋值英文key与值到新对象
          // item2为中文 obj[item2]为英文
          // console.log(obj[item2])
          // obj[item2]为obj所对应的键
          // item[item2]为item所对应的值
          newObj[obj[item2]] = item[item2]
          if (obj[item2] === 'timeOfEntry' || obj[item2] === 'correctionTime') {
            newObj[obj[item2]] = this.chnageDate(item[item2])
          }
        })
        return newObj
      })
      // 发送请求将数据添加
      await sysUserBatch(arr)
      // 添加成功提示成功
      this.$message.success('导入成功')
      // 跳转到employees页面
      this.$router.push('/employees')
      console.log(header, results, arr)
    },
    // 将excel时间转换为标准时间
    chnageDate(num) {
      const t = new Date((num - 1) * 24 * 60 * 60 * 1000 - 8 * 60 * 60 * 1000)
      t.setYear(t.getFullYear() - 70)
      return t
    }
  }
}
</script>
<style lang="less" scoped></style>
